package com.silverhaze.diamond.client.ui.dialogs;

import com.silverhaze.commons.db.datasource.ObjectEntity;
import com.silverhaze.commons.helpers.CommonUIHelper;
import com.silverhaze.diamond.client.data.dao.DAOLocator;
import com.silverhaze.diamond.client.ui.dialogs.view.ViewDialog;
import com.silverhaze.diamond.common.entity.Service;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

/**
 * SystemUser: Babanin
 * Date: 11.11.2008
 * Time: 22:08:31
 */
public class ServiceNumberDialog extends AbstractDialog {

    private JComboBox numberField;

    public ServiceNumberDialog(Frame owner) {
        super(owner);
        initView();
    }

    private void initView() {
        setTitle("Поиск сервиса");

        numberField = new JComboBox(getAllIds());
        numberField.setEditable(true);

        setLayout(new BorderLayout());
        add(CommonUIHelper.createHorizontalBox("Номер сервиса: ", 2, numberField, 2, new JButton(new AbstractAction("OK") {
            public void actionPerformed(ActionEvent e) {
                okPressed();
            }
        }), 2, new JButton(new AbstractAction("Отмена") {
            public void actionPerformed(ActionEvent e) {
                cancelPressed();
            }
        })), BorderLayout.CENTER);

        getRootPane().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        pack();

        setLocationRelativeTo(null);
    }

    protected void okPressed() {
        Object selectedValue = numberField.getSelectedItem();

        if (selectedValue == null) {
            JOptionPane.showMessageDialog(getOwner(), "Не выбран номер сервиса", "Ошибка",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            int id = Integer.parseInt(selectedValue.toString().trim());
            if (id <= 0) {
                throw new NumberFormatException();
            }

            for (ObjectEntity e : DAOLocator.getInstance().getServices()) {
                Service service = (Service) e;

                if (service.getId() == id) {
                    ViewDialog.service(service);
                    dispose();
                    return;
                }
            }

            JOptionPane.showMessageDialog(getOwner(), "Нет сервиса с номером: " + id, "Ошибка",
                    JOptionPane.ERROR_MESSAGE);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(getOwner(), "Номер сервиса должен быть положительным целым числом",
                    "Ошибка", JOptionPane.ERROR_MESSAGE);
        }

    }

    public ComboBoxModel getAllIds() {
        java.util.List<ObjectEntity> list = DAOLocator.getInstance().getServices();
        String[] data = new String[list.size()];

        int i = 0;
        for (ObjectEntity service : list) {
            data[i++] = "" + service.getId();
        }

        return new DefaultComboBoxModel(data);
    }
}

